package com.lupus.persistence.sql;

import java.util.HashMap;

import com.lupus.common.CommonFactory;

public class IdentityGenerator {
	private static HashMap<String,IdentityInfo> identityMap = new HashMap<String,IdentityInfo>();
	private static final int POOL_SIZE = 20;
	
	public static synchronized int getNextIndetity (String tableName){
		IdentityGenerator.IdentityInfo identityInfo = null;
		if(identityMap.containsKey(tableName)){
			identityInfo = identityMap.get(tableName);
		}else{
			identityInfo = new IdentityGenerator().getIdentityInfo(POOL_SIZE,tableName);
			identityMap.put(tableName,identityInfo);
		}
		return identityInfo.getNextIndetity();
	}
	private IdentityInfo getIdentityInfo(int poolSize,String tableName){
		return  new IdentityInfo(poolSize,tableName);
	}
	
	class IdentityInfo{
		private int poolSize;
		private int nextIdentity;
		private int identityMax;
		private String tableName;
		public IdentityInfo(int poolSize,String tableName){
			this.poolSize = poolSize;
			this.tableName = tableName;
		}
		private void getIdentity(){
			CommonFactory.buildAction("update","CURID=CURID+"+this.poolSize,"BAS_TABLEID","TABLENAME='"+this.tableName+"'",null,null);
			CommonFactory.buildAction("query","CURID","BAS_TABLEID","TABLENAME='"+this.tableName+"'",null,null);
		}
		public int getNextIndetity(){
			if(nextIdentity>identityMax){
				this.getIdentity();
			}
			return nextIdentity++;
		}
	}
}
